import NProgress from "nprogress";
const base_url = "http://www.pudge.wang:3080/api";

const http = {
  get(url, params) {
    // http://www.pudge.wang:3080/api/rated/list?a=3&b=4
    // {a:3,b:4} => ?a=3&b=4

    if (params) {
      const arr = Object.keys(params); // arr: ["a", "b"]
      const arr2 = arr.map((item) => item + "=" + params[item]); // arr2: ["a=3", "b=4"]
      const str = arr2.join("&"); // str: "a=3&b=4"
      url += "?" + str;
    }

    return fetch(base_url + url)
      .then((response) => response.json())
      .then((res) => {
        if (res.status === 0) {
          return res;
        }
      });
  },
  post(url, data) {
    NProgress.start();
    return fetch(base_url + url, {
      method: "post",
      headers: {
        "content-type": "application/json",
      },
      body: JSON.stringify(data),
    })
      .then((response) => response.json())
      .then((res) => {
        NProgress.done();
        if (res.status === 0) {
          return res;
        }
      });
  },
};

export default http;
